import React, { createContext, useContext, useState, useEffect, type ReactNode } from 'react';
import http from './api/http'
import type { IAuthUser  } from './types/system' //用户信息类型

// 认证上下文类型定义
interface AuthContextType {
  user: IAuthUser | null;
  loading: boolean;
  login: (username: string, password: string) => Promise<boolean>;
  logout: () => void;
  isAuthenticated: boolean;
}

// 创建上下文
const AuthContext = createContext<AuthContextType | undefined>(undefined);

// 认证提供者组件
const AuthProvider: React.FC<{ children: ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<IAuthUser | null>(null);
  const [loading, setLoading] = useState(true);

  // 初始化 - 从本地存储中恢复用户状态
  useEffect(() => {
    try {
      const storedUser = sessionStorage.getItem('user');
      if (storedUser) {
        setUser(JSON.parse(storedUser));
      }
    } catch (error) {
      console.error('Failed to load user from sessionStorage', error);
    } finally {
      setLoading(false);
    }
  }, []);

  // 登录方法
  const login = async (username: string, password: string): Promise<boolean> => {
    
    const response = await http.get<IAuthUser>('Authentication', { loginName: username, loginPwd: password })
    if (response.code == "1") {
      //调用 函数 设置Token
      setUser(response.data)
      sessionStorage.setItem('user', JSON.stringify(response.data));
      return true;
    } else {
      return false;
    }
  };

  // 登出方法
  const logout = () => {
    setUser(null);
    sessionStorage.removeItem('user');
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        loading,
        login,
        logout,
        isAuthenticated: !!user
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

// 自定义Hook，方便使用认证上下文
export const useAuth = () => {
  const context = useContext(AuthContext);
  if (context === undefined) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};


export default AuthProvider